package com.mustafaiev.tair.cts.tapestry.pages.batches;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import com.mustafaiev.tair.cts.enums.BasketsBatchState;
import com.mustafaiev.tair.cts.exeptions.DataNotStoredException;
import com.mustafaiev.tair.cts.facade.IBasketFacade;
import com.mustafaiev.tair.cts.facade.IBasketsBatchFacade;
import com.mustafaiev.tair.cts.factory.ICostTrackingSystemFacadeFactory;
import com.mustafaiev.tair.cts.tapestry.dto.BasketDTO;
import com.mustafaiev.tair.cts.tapestry.dto.BasketsBatchDTO;

public class CreateBasketsBatch {

	@Inject
	private ICostTrackingSystemFacadeFactory facadeFactory;

	@InjectPage
	private Index batchesPage;

	@Property
	private BeanModel<BasketDTO> basketGridModel;

	@Inject
	private BeanModelSource beanModelSource;

	@Inject
	private Messages messages;

	@Component(id = "createBasketsBatchForm")
	private Form form;

	@Property
	@Persist
	private List<BasketDTO> baskets;

	@Property
	@Persist
	private List<BasketDTO> basketsToChange;

	@Property
	@Persist
	private BasketDTO basket;

	@Property
	@Persist
	private BasketsBatchDTO batch;

	public boolean isCheck() {
		return false;
	}

	public void setCheck(final boolean check) {
		if (check) {
			this.basketsToChange.add(this.basket);
		}
	}

	@SetupRender
	void setupRender() {
		this.batch = new BasketsBatchDTO();
		this.basketsToChange = new ArrayList<BasketDTO>();
		this.baskets = getBasketsFacade().retrieveNonBatchedBaskets();
	}

	public Object onValidateFromCreateBasketsBatchForm() {
		if (this.basketsToChange.size() == 0) {
			this.form
					.recordError("At least one basket should be checked for batching");
		}
		return null;
	}

	public Object onSuccessFromCreateBasketsBatchForm() {
		try {
			this.batch.setBatchState(BasketsBatchState.IN_PROGRESS);
			this.batch.setBaskets(this.basketsToChange);
			getBasketsBatchFacade().save(this.batch);
		} catch (final DataNotStoredException e) {
			this.form.recordError(e.getLocalizedMessage());
		}
		return this.batchesPage;
	}

	@OnEvent(value = "back")
	Object goBack() {
		return this.batchesPage;
	}

	private IBasketFacade getBasketsFacade() {
		return this.facadeFactory.getFacade(IBasketFacade.class);
	}

	private IBasketsBatchFacade getBasketsBatchFacade() {
		return this.facadeFactory.getFacade(IBasketsBatchFacade.class);
	}

}
